package com.example.hospital.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.hospital.constant.UserConstants;
import com.example.hospital.dto.DoctorQuery;
import com.example.hospital.dto.LoginForm;
import com.example.hospital.dto.Result;
import com.example.hospital.entity.Doctor;
import com.example.hospital.service.DoctorService;
import com.example.hospital.mapper.DoctorMapper;
import com.example.hospital.util.JwtHelper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author Oreki
 * @description 针对表【doctor】的数据库操作Service实现
 * @createDate 2024-12-27 16:53:20
 */
@Service
public class DoctorServiceImpl extends ServiceImpl<DoctorMapper, Doctor>
        implements DoctorService {

    @Override
    public Result<Map<String, String>> login(LoginForm loginForm) {
        if (loginForm == null) {
            return Result.fail("登录信息不能为空");
        }
        String phone = loginForm.getPhone();
        String password = loginForm.getPassword();
        if (StrUtil.isEmpty(phone) || StrUtil.isEmpty(password)) {
            return Result.fail("手机号或密码不能为空");
        }
        Doctor doctor = this.getDoctorByPhoneNumber(phone);
        if (doctor == null || !password.equals(doctor.getPassword())) {
            return Result.fail("手机号或密码错误");
        }
        String token = JwtHelper.createToken(phone, UserConstants.Role.DOCTOR);
        return Result.success(Map.of("token", token, "id", doctor.getDoctorId().toString(), "name", doctor.getName()));
    }

    @Override
    public Doctor getDoctorByPhoneNumber(String phoneNumber) {
        if (StrUtil.isEmpty(phoneNumber)) {
            return null;
        }
        return this.lambdaQuery().eq(Doctor::getPhoneNumber, phoneNumber).one();
    }

    @Override
    public List<Doctor> getDoctorByDepartment(String specialty) {
        if (StrUtil.isEmpty(specialty)) {
            return null;
        }
        return this.lambdaQuery().eq(Doctor::getSpecialty, specialty).list();
    }

    @Override
    public List<Doctor> listDoctors(DoctorQuery doctorQuery) {
        if (doctorQuery == null) {
            return this.list();
        }
        String name = doctorQuery.getName();
        String specialty = doctorQuery.getSpecialty();
        String phoneNumber = doctorQuery.getPhoneNumber();
        String email = doctorQuery.getEmail();
        String roomNumber = doctorQuery.getRoomNumber();
        return this.lambdaQuery()
                .like(StrUtil.isNotEmpty(name), Doctor::getName, name)
                .eq(StrUtil.isNotEmpty(specialty), Doctor::getSpecialty, specialty)
                .eq(StrUtil.isNotEmpty(phoneNumber), Doctor::getPhoneNumber, phoneNumber)
                .eq(StrUtil.isNotEmpty(email), Doctor::getEmail, email)
                .eq(StrUtil.isNotEmpty(roomNumber), Doctor::getRoomNumber, roomNumber)
                .list();
    }
}




